from fdfs_client.client import Fdfs_client
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from goods.models import SPU, Brand, GoodsCategory
from meiduo_admin.good.spu_serializers import SPUSerializer, SPUBrandSerializer, SPUCategorySerializer
from meiduo_admin.my_paginate import MyPageNumberPagination
from rest_framework.response import Response
from django.conf import settings

class SPUViewSet(ModelViewSet):
    pagination_class = MyPageNumberPagination
    queryset = SPU.objects.all()
    serializer_class = SPUSerializer


class SPUBrandListView(ListAPIView):
    queryset = Brand.objects.all()
    serializer_class = SPUBrandSerializer


class SPUCategoryListView(ListAPIView):
    queryset = GoodsCategory.objects.filter(parent=None).all()
    serializer_class = SPUCategorySerializer

class SubsCategoryListView(ListAPIView):
    serializer_class = SPUCategorySerializer

    def get_queryset(self):
        category_id = self.kwargs.get('category_id')
        return GoodsCategory.objects.filter(parent=category_id).all()


class SPUDetailImageView(APIView):
    def post(self,request):
        # 1.接收数据
        image = request.FILES.get('image')
        # 2.检验数据
        if not image:
            return Response('参数不全,图片上传失败',status=400)
        # 3.图片上传
        client = Fdfs_client(settings.CONFIG_URL)
        result = client.upload_by_buffer(image.read())

        if result['Status']!='Upload successed.':
            return Response('上传失败',status=400)

        # 4.返回响应
        img_url = settings.BASE_URL+ result['Remote file_id']
        return Response({'img_url':img_url})